import roleModel from "../../../models/system/roleModel.js";
import userModel from "../../../models/system/userModel.js";
import {Op, QueryTypes, Sequelize} from "sequelize";
import {Result} from "../../../utils/result.js";
import {sequelize} from "../../../config/mysqlDB.js";

const userService = {
  async addUser(username, password, roleId) {
    return userModel.create({username, password, roleId});
  },

  async delUser(id) {
    return userModel.destroy({
      where: {
        id,
      }
    });
  },

  async getUser(username) {
    let res = await userModel.findAll({
      where: {
        username: {
          [Op.like]: `%${username}`
        }
      }
    });
    return Result.success(res);
  },
  async getUserByOrg() {
    let sql = `select u.* from user u left join role r on u.role_id = r.id`
    let res = await sequelize.query(sql, {
      // model: userModel,
      // mapToModel: true,
      raw: true,
      type: QueryTypes.SELECT,
    })
    // res = mapKeysToCamelCase(res);
    return Result.success(res);
  },
  async updateUserById(username) {
    let sql = `update user set username = '${username}' where id = 1`
    let res = await sequelize.query(sql, {
      type: QueryTypes.UPDATE,
    })
    return Result.success(res);
  },
  async getUserAndRoleName(username) {
    /*let sql = `select u.*, r.name from user u left join role r on u.role_id = r.id where u.username = '${username}'`
    let res = await sequelize.query(sql, {
      type: QueryTypes.SELECT,
    })
    return Result.success(res);*/
    /*
    * 设置别名的方式为 [field,alias]
    *
    * */
    let res = await userModel.findAll({
      attributes: [
        'id',
        ['username', 'u_name'],
      ],
      include: [
        {
          model: roleModel,
          attributes: ['name'],
        }
      ],
      where: {
        username,
      }
    })
    return Result.success(res);
  }
}
export default userService;
